package com.xlh.outside;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xlh.Model.ButCmdsModel;
import com.xlh.Utils.Constant;
import com.xlh.Utils.FUti;
import com.xlh.Utils.MudProtocol;
import com.xlh.Utils.SocketClient;
import com.xlh.adapter.CenterAdapter;
import com.xlh.adapter.ChatAdapter;
import com.xlh.adapter.FloatRightButListAdapter;
import com.xlh.adapter.GridViewAndListViewAdapter;
import com.xlh.adapter.NPCAdapter;
import com.xlh.adapter.OtherExitsAdapter;
import com.xlh.adapter.TitleAdapter;
import com.xlh.adapter.UserBtnAreaAdapter;
import com.xlh.bean.CenterText;
import com.xlh.bean.CharBean;
import com.xlh.bean.DataBase.ButCmd;
import com.xlh.bean.TitleBean;
import com.xlh.broadcast.WzBroadcastReceiver;
import com.xlh.fgs.BtnsFg.OnItemClick;
import com.xlh.fgs.ColorPickerFragment;
import com.xlh.fgs.ESA_003Fg.OnSendActionToServiceListener;
import com.xlh.fgs.CreateRoleFg;
import com.xlh.fgs.SetColorMainFragment;
import com.xlh.fgs.UserFg;
import com.xlh.interf.IActivity;
import com.xlh.interf.ITakeMessage;
import com.xlh.interf.TelnetHandler;
import com.xlh.lib.Core.RenderCore;
import com.xlh.lib.Core.ServerCommHelper;
import com.xlh.server.protocol.support.app.ReConnectServer;
import com.xlh.server.protocol.support.json.ButsGropServer;
import com.xlh.server.protocol.support.json.ChannelServer;
import com.xlh.server.protocol.support.json.EnvObjectsStateAttrServer;
import com.xlh.server.protocol.support.json.ExitsServer;
import com.xlh.server.protocol.support.json.HPServer;
import com.xlh.server.protocol.support.json.InputBoxServer;
import com.xlh.server.protocol.support.json.IsEnLoginServer;
import com.xlh.server.protocol.support.json.LogindServer;
import com.xlh.server.protocol.support.json.LongBoxLBServer;
import com.xlh.server.protocol.support.json.LongBoxRBServer;
import com.xlh.server.protocol.support.json.MapServer;
import com.xlh.server.protocol.support.json.NotificationServer;
import com.xlh.server.protocol.support.json.OncmdServer;
import com.xlh.server.protocol.support.json.OpenLongBoxServer;
import com.xlh.server.protocol.support.json.RegBoxServer;
import com.xlh.server.protocol.support.json.RemoveAllExitServer;
import com.xlh.server.protocol.support.json.RemoveExitServer;
import com.xlh.server.protocol.support.json.RemoveRoomObejctServer;
import com.xlh.server.protocol.support.json.RightFiexButsServer;
import com.xlh.server.protocol.support.json.RoomDescServer;
import com.xlh.server.protocol.support.json.RoomObjectServer;
import com.xlh.server.protocol.support.json.RoomTitleServer;
import com.xlh.server.protocol.support.json.SysExitServer;
import com.xlh.server.protocol.support.json.WindowServer;
import com.xlh.service.MyService;
import com.xlh.thread.CheckTelnetConnTask;
;
import com.xlh.view.FFListView;
import com.xlh.view.FloatingMenu;
import com.xlh.view.MyGridView;
import com.xlh.view.MyListView;
import com.xlh.view.WzTextView;
import com.xlh.view.manager.FloatRightButListViewManager;
import com.xlh.view.manager.OtherExitsViewManager;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import net.nightwhistler.htmlspanner.HtmlSpanner;

/**
* 多彩带点击的文字
* http://www.jianshu.com/p/f004300c6920
*
*
* okHTTP
* http://blog.csdn.net/lin857/article/details/54694441
* fg 替换方法
* getFragmentManager().beginTransaction().replace(R.id.mcontainer, eFg).commitAllowingStateLoss();
 *
 *
 * Android开发人员不得不收集的代码(持续更新中)
 * https://www.jianshu.com/p/72494773aace
 **/







	@SuppressLint({"HandlerLeak", "ResourceAsColor", "ClickableViewAccessibility","JavascriptInterface"})
	public class MainActivity extends BaseActivity
			implements TelnetHandler, OnSendActionToServiceListener, OnItemClick,IActivity {






	private MainActivity me = this;
	public boolean isReconnectStatus() {
		return reconnectStatus;
	}


	public void setReconnectStatus(boolean reconnectStatus) {
		this.reconnectStatus = reconnectStatus;
	}

	private boolean telnetStarted = false;
	private boolean loginStat = false;

	public HashMap<String, ITakeMessage> getTakeMessageHandler() {
		return takeMessageHandler;
	}

	public void setTakeMessageHandler(HashMap<String, ITakeMessage> takeMessageHandler) {
		this.takeMessageHandler = takeMessageHandler;
	}

	//协议处理对象
	private HashMap<String,ITakeMessage> takeMessageHandler = new HashMap<String,ITakeMessage>();



	public SocketClient getmSocketClient() {
		return mSocketClient;
	}


	public void setmSocketClient(SocketClient mSocketClient) {
		this.mSocketClient = mSocketClient;
	}



	public int getSceneViewOldHeight() {
		return sceneViewOldHeight;
	}

	public void setSceneViewOldHeight(int sceneViewOldHeight) {
		this.sceneViewOldHeight = sceneViewOldHeight;
	}

	public boolean isSceneViewHide() {
		return sceneViewHide;
	}

	public void setSceneViewHide(boolean sceneViewHide) {
		this.sceneViewHide = sceneViewHide;
	}

	public ServerCommHelper getServerCommHelper() {
		return serverCommHelper;
	}

	public void setServerCommHelper(ServerCommHelper serverCommHelper) {
		this.serverCommHelper = serverCommHelper;
	}
	//Server帮助类
	private ServerCommHelper serverCommHelper;

	private HashMap<String,ITakeMessage> appMessageHandler = new HashMap<String,ITakeMessage>();

	public HtmlSpanner getHtmlSpanner() {
		return htmlSpanner;
	}

	public void setHtmlSpanner(HtmlSpanner htmlSpanner) {
		this.htmlSpanner = htmlSpanner;
	}

	private HtmlSpanner htmlSpanner;



//	@SuppressLint("ResourceType")
//	@Override
//	protected void onResume() {
//		super.onResume();
//		RelativeLayout layout = (RelativeLayout)findViewById(R.layout.activity_main);
//		InputStream is ;
//		BitmapFactory.Options opt = new BitmapFactory.Options();
//		opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
//		opt.inPurgeable = true;
//		opt.inInputShareable = true;
//		opt.inSampleSize = 2;
//		is= getResources().openRawResource(R.drawable.mianbg);
//		Bitmap bm = BitmapFactory.decodeStream(is, null, opt);
//		BitmapDrawable bd = new BitmapDrawable(getResources(), bm);
//		layout.setBackgroundDrawable(bd);
//	}



	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		//无title
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//全屏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);

		//初始化高宽
		WindowManager wm = this.getWindowManager();
		setApp(  (WzApplication)getApplication() );
		getApp().setWndHeight( wm.getDefaultDisplay().getHeight()  );
		getApp().setWndWidth(  wm.getDefaultDisplay().getWidth() );
		setContentView( R.layout.activity_main );
		//初始化颜色设定
		Constant.initAppColor(this);
		setServerCommHelper(new ServerCommHelper(this));
		takeMessageHandler.put("WindowServer",				new WindowServer(this));
		takeMessageHandler.put("ChannelServer",				new ChannelServer(this));
		takeMessageHandler.put("ExitsServer",				new ExitsServer(this));
		takeMessageHandler.put("HPServer",					new HPServer(this));
		takeMessageHandler.put("RoomDescServer",			new RoomDescServer(this));
		takeMessageHandler.put("ButsGropServer",			new ButsGropServer(this));
		takeMessageHandler.put("RoomTitleServer",			new RoomTitleServer(this));
		takeMessageHandler.put("LogindServer",				new LogindServer(this));
		takeMessageHandler.put("OncmdServer",				new OncmdServer(this));
		takeMessageHandler.put("RoomObjectServer",			new RoomObjectServer(this));
		takeMessageHandler.put("RemoveRoomObejctServer",	new RemoveRoomObejctServer(this));
		takeMessageHandler.put("OpenLongBoxServer",			new OpenLongBoxServer(this));
		takeMessageHandler.put("LongBoxRBServer",			new LongBoxRBServer(this));
		takeMessageHandler.put("LongBoxLBServer",			new LongBoxLBServer(this));
		takeMessageHandler.put("InputBoxServer",			new InputBoxServer(this));
		takeMessageHandler.put("MapServer",					new MapServer(this));
		takeMessageHandler.put("SysExitServer",				new SysExitServer(this));
		takeMessageHandler.put("RegBoxServer",				new RegBoxServer(this));
		takeMessageHandler.put("EnvObjectsStateAttrServer",	new EnvObjectsStateAttrServer(this));
		takeMessageHandler.put("RightFiexButsServer",		new RightFiexButsServer(this));
		takeMessageHandler.put("RemoveExitServer",			new RemoveExitServer(this));
		takeMessageHandler.put("RemoveAllExitServer",		new RemoveAllExitServer(this));
		takeMessageHandler.put("NotificationServer",		new NotificationServer(this));
		takeMessageHandler.put("IsEnLoginServer",			new IsEnLoginServer(this));





		//APP内部handler消息服务
		appMessageHandler.put("ReConnectServer",			new ReConnectServer(this));

		this.setHtmlSpanner(new HtmlSpanner(this));

		startService();

		if (!runing) runing = true;

			//有初始化参数..所以必须在前面...
			init();
			mSocketClient 		= new SocketClient(MainActivity.this);
			mSocketClient.host 	= getApp().getActiveServer();
			mSocketClient.port 	= Integer.parseInt(getApp().getActivePort());
			//mSocketClient.setCharSet(getApp().getCharSet());
			//setAppColor();
			setExitButEvt();
			initWebview();


	}




	/**
	 * 初始化浮动菜单控件
	 */
	private void initFloatingMenu() {
		floating.setOnItemMenuClickListener(new FloatingMenu.OnItemMenuClickListener() {
			@Override
			public void onItemMenuClick(View view, int position) {
				Toast.makeText(MainActivity.this, "子菜单 - " + position, Toast.LENGTH_SHORT).show();
			}
		});
	}

	/**
	 * 设置ListView中的数据
	 */
	private void setFloatRightListView() {








	}

	public void startService(){

		/**
		 * 服务启动后
		 * 需要1分钟后才能正式进入后台服务
		 */
		Process.myUid();
		Process.myTid();
		Process.myPid();
		if (!isWorked()) {
			Intent intent = new Intent(MainActivity.this, MyService.class);
			startService(intent);
		}
		// server end
	}


	public void startNetServer(){
		//连接服务器 开始通信 防止重复连接
		if(mSocketClient.isStarted()) return;

		mSocketClient.start();

//		Thread th = new Thread(new CheckTelnetConnTask(this));
//		th.start();
	}

	private WebView webView;


	public void initWebview() {



		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setDefaultTextEncodingName("utf-8");


		webView.addJavascriptInterface(this, "App");

		// 禁用WEBVIEW滚动
		webView.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent evt) {

				return (evt.getAction() == MotionEvent.ACTION_MOVE);

			}
		});

		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {

				if (newProgress == 100) {
					// 网页加载完成
					// documentLoaded();
					// 注意onProgressChanged 会被触发两次
					startNetServer();


				}

			}


		});

		// WebView加载web资源
		//webView.loadUrl(siteUrl);
		 webView.loadUrl("file:///android_asset/index.html");
		// 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
		//
		// webView.setDownloadListener(new MyWebViewDownLoadListener());

		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// TODO Auto-generated method stub
				// 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器



				return true;
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				// 这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
				// view.loadUrl(file:///android_asset/error.html );
				// wNh.NoticeErr(description);
			}

		});
		// 禁用长按复制
		webView.setOnLongClickListener(new View.OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {
				// TODO Auto-generated method stub
				return true;
			}

		});

	}

	public OtherExitsViewManager getOtherExitsViewManager() {
		return otherExitsViewManager;
	}

	public void setOtherExitsViewManager(OtherExitsViewManager otherExitsViewManager) {
		this.otherExitsViewManager = otherExitsViewManager;
	}

	private OtherExitsViewManager otherExitsViewManager;

	public FloatRightButListViewManager getFloatRightButListViewManager() {
		return floatRightButListViewManager;
	}

	public void setFloatRightButListViewManager(FloatRightButListViewManager floatRightButListViewManager) {
		this.floatRightButListViewManager = floatRightButListViewManager;
	}

	private FloatRightButListViewManager floatRightButListViewManager;


	private void init() {
		webView 			= (WebView) findViewById(R.id.webView);
		etInput				= (EditText) findViewById(R.id.mIn);
		inputBoxBut 		= (Button) findViewById(R.id.mSend);

		// 地图焦点问题
		mMapLayout 			= (LinearLayout) findViewById(R.id.alertMap);
		// 场景描述
		tvContent 			= (TextView) findViewById(R.id.tvContent);
		//NPC列表
		mTitleList 			= (ListView) findViewById(R.id.mLeftList);
		// 100聊天信息
		mChatList 			= (ListView) findViewById(R.id.mChatList);
		// 中间场景
		mCenterList 		= (ListView) findViewById(R.id.mCenterList);
		// 自定义按钮组
		mBtnGroup 			= (LinearLayout) findViewById(R.id.mBtnGroup);
		//其他出口(2.5D出口)
		mLeftExitGroup 		= (ListView) findViewById(R.id.mLeftExitGroup);
		lvFloatRightList 	= (ListView) findViewById(R.id.lvFloatMenu);
		// 切换操作、附近地图
		tvTop 				= (TextView) findViewById(R.id.tvTop);
		tvBottom 			= (TextView) findViewById(R.id.tvBottom);

		// 弹出框初始化
		//弹出框关闭按钮
		mAlertClose 		= (ImageView) findViewById(R.id.mAlertClose);
		//弹出框内文字
		mAlertText 			= (TextView) findViewById(R.id.mAlertTv);
		//008列表
		mAlertList 			= (MyListView) findViewById(R.id.m008List);
		//009列表
		mAlertGrid 			= (MyGridView) findViewById(R.id.m009Grid);
		mL 					= (LinearLayout) findViewById(R.id.mAlertList);
		//输入框下面的文字
		mAlertInputBigText 	= (TextView) findViewById(R.id.mAlertInputBigText);

		//弹出框右侧文本
		m091Tv 				=  (WzTextView) findViewById(R.id.m091tv);


		// 地图
		tvMap 				= (TextView) findViewById(R.id.map);
		ivCloseMap 			= (ImageView) findViewById(R.id.mMapClose);
		mInputLayout 		= (LinearLayout) findViewById(R.id.inputLayout);

		rlCenterRight 		= (RelativeLayout)findViewById(R.id.Center);

		gamescene 			= (LinearLayout) findViewById(R.id.gamescene);
		fullsceneContainer 	=  (LinearLayout) findViewById(R.id.fullscene_container);

		//008绑定setAdapter
		mAlertList.setDataAdapter(new GridViewAndListViewAdapter(this, null));
		//009绑定setAdapter
		mAlertGrid.setDataAdapter(new GridViewAndListViewAdapter(this, null));


		mTitleData = new ArrayList<TitleBean>();
		mTitleAdapter = new NPCAdapter(this, mTitleData);
		mTitleList.setAdapter(mTitleAdapter);




		//mChatList.setVisibility(View.GONE);//默认不显示聊天框
		mChatBean = new ArrayList<CharBean>();
		mChatAdapter = new ChatAdapter(this, mChatBean);
		mChatList.setAdapter(mChatAdapter);
		//mChatList.setOnItemClickListener(onChatListItemClickListener);
		//frament
		setUserFg(new UserFg());


		// 颜色值
		mColors = Constant.getColorMap();
		mColorList = Constant.getColorList();

		mCenterData = new ArrayList<CenterText>();
		mCenterAdapter = new CenterAdapter(this, mCenterData);
		mCenterList.setAdapter(mCenterAdapter);

		mCenterList.setClickable(false);


		// 三维出口
		mDirs = new HashMap<String, String>();
		mPlaceKey = new ArrayList<String>();



		//其他出口VIEW管理器
		otherExitsViewManager = new OtherExitsViewManager(
				this,
				mLeftExitGroup,
				new OtherExitsAdapter(this,new ArrayList<TitleBean>())
		);



		//右边浮动按钮管理器
		floatRightButListViewManager = new FloatRightButListViewManager(
				this,
				lvFloatRightList,
				new FloatRightButListAdapter(this,new ArrayList<TitleBean>())
		);



		//floating = (FloatingMenu) findViewById(R.id.floating);
		//浮动扇形菜单
		//initFloatingMenu();
		setFloatRightListView();


//
//		places = new ArrayList<String>();
//		addPlaceRegex();


		tvTop.setOnClickListener(onAdditionalButClickListener);
		tvBottom.setOnClickListener(onAdditionalButClickListener);



		colorPickerFragment = new ColorPickerFragment();
		setColorMainFragment = new SetColorMainFragment();


		setSceneViewHide(false);


		//场景描述框点击事件
		tvContent.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isSceneViewHide()){
					setSceneViewHide(false);
					tvContent.getLayoutParams().height = getSceneViewOldHeight();
				}else{
					//只保存一次初始高度 否则会有问题
					if(getSceneViewOldHeight()<=0){
						setSceneViewOldHeight(tvContent.getLayoutParams().height);
					}


					tvContent.getLayoutParams().height = FUti.dip2px(MainActivity.this,20);
					//tvContent.set
					setSceneViewHide(true);
				}

			}
		});
		//地图框的关闭按钮
		ivCloseMap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mMapLayout.getVisibility() == View.VISIBLE) {
					mMapLayout.setVisibility(View.INVISIBLE);
					mMapLayout.setClickable(false);
				}
				lvFloatRightList.setVisibility(View.VISIBLE);
			}
		});


		//弹出框关闭的关闭按钮
		//清除008 009 以及弹出框内内容
		mAlertClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				//不管是否显示清除008

				me.getmAlertGrid().getDataAdapter().clear();
				me.getmAlertList().getDataAdapter().clear();




				if (mAlertLayout.getVisibility() == View.VISIBLE) {
					mAlertLayout.setVisibility(View.INVISIBLE);
					mAlertLayout.setClickable(false);
				}
				lvFloatRightList.setVisibility(View.VISIBLE);


			}
		});


				mAlertLayout = (ScrollView) findViewById(R.id.mAlertLayout);
		mAlertLayout.setClickable(false);






		// 其他出口设置点击事件
		this.getOtherExitsViewManager().getView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
				// TODO Auto-generated method stub
				//因为一次BUG 注释掉这里..
				//mTitleData.clear();
				OtherExitsAdapter e  = (OtherExitsAdapter)me.getOtherExitsViewManager().getDataAdapter();
				mSocketClient.sendMsg(e.getItem(position).getmAction());
			}
		});
		//20180701注释 突然报错
		mTitleList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

				me.getmAlertList().getDataAdapter().clear();
				me.getmAlertGrid().getDataAdapter().clear();

				mSocketClient.sendMsg(mTitleAdapter.getItem(position).getmAction());

			}
		});


		//初始化自定义按键数据

		ButCmdsModel butCmdsModel = new ButCmdsModel(this);
		this.setDiyButs(butCmdsModel.getList());

		initDirControl();
		//隐藏弹出BOX
		closeAlertBox();

		renderCore = new RenderCore(this);

		//界面组件绑定完成之后执行的事情
		for(String e: takeMessageHandler.keySet() ){
			takeMessageHandler.get(e).atViewLoadAfterInit();
		}


	}


		/**
	 	* 8
		 * 页面初始化时会调用此函数...注意是系统调用
	 	* 只有一次
	 	*/
		@Override
		public void onWindowFocusChanged(boolean hasFocus) {
			// TODO Auto-generated method stub
			super.onWindowFocusChanged(hasFocus);
			 //DisplayMetrics displayMetr


			//getWindowManager().getDefaultDisplay().getMetics = new DisplayMetrics();rics(displayMetrics);

		if (hasFocus) {
			//左侧NPC列表高度
			int appHeight = mL.getHeight();
			int mapHeight = mTitleList.getHeight();




			if (mAlertGrid != null && mAlertList != null) {



				//int height = (int) (displayMetrics.heightPixels * 0.35);
				//int width = (int) (displayMetrics.widthPixels * 0.35);

				int height = (int) (getApp().getWndWidth() * 0.35);
				int width = (int) (getApp().getWndWidth() * 0.35);


				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height);
				mAlertLayout.setLayoutParams(lp);
				LayoutParams gp01 = new LayoutParams(0, height - appHeight);
				LayoutParams gp02 = new LayoutParams(0, height - appHeight);
				LayoutParams mp = new LayoutParams(LayoutParams.MATCH_PARENT, mapHeight );
				gp01.weight = list008Weight;
				gp02.weight = 3;

				mAlertList.setLayoutParams(gp01);
				mAlertGrid.setLayoutParams(gp02);




				//mMapLayout.setLayoutParams(lp);a
				//主要出口按钮区域高度
				//ViewGroup.LayoutParams exitsParam = exitsGridview.getLayoutParams();

				//exitsParam.width = FUti.dip2px(MainActivity.this,width*65/100);
				//设置弹出框高度
				ViewGroup.LayoutParams alertBoxParam = mAlertLayout.getLayoutParams();
				alertBoxParam.height = FUti.dip2px(MainActivity.this,mapHeight) ;
				mMapLayout.getLayoutParams().height = FUti.dip2px(MainActivity.this,height - appHeight) ;
				//mMapLayout.getLayoutParams().width = mCenterList.getWidth();
			}

		}



	}

	public Handler getHandler() {
		return handler;
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	private Handler handler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {

				case 1://仅处理消息
					//当what 为1 时表示开始轮询消息 并交给dealData做接收处理和分析
					//dealData进行处理

					Bundle b = msg.getData();
					String tmpString = b.getString("msg");
					//tmpString = tmpString.replaceAll("\\[0\\;0m",Constant.NOR);

					final String result = tmpString;
					putMessage(result);
					//兼容指令处理
					//dealData(result, handler);
					break;

				case 2:

					Bundle bundle = msg.getData();
					String str = bundle.getString("msg");
					onTakeJavascriptMessageByHandler(str);
					break;

			}
		}
	};





	//右边场景内容列表框更新

	public Handler getRenderDataToCenterListHandler() {
		return renderDataToCenterListHandler;
	}

	public void setRenderDataToCenterListHandler(Handler renderDataToCenterListHandler) {
		this.renderDataToCenterListHandler = renderDataToCenterListHandler;
	}

	public Handler renderDataToCenterListHandler;







	//SOCKET调用
	@Override
	public void OnRecvComplete(String s) {
		Message msg = new Message();
		Bundle data = new Bundle();

		data.putString("msg", s);

		msg.setData(data);
		msg.what = 1;
		handler.sendMessage(msg);
		Log.i("OnRecvComplete result：", s);
		Log.i("scene：", String.format("宽度:%d 高度:%d",getApp().getWndWidth(),getApp().getWndHeight()));
	}

	JsonObject returnData;
	String messageData;
	//该函数被handler调用
	public void onTakeJavascriptMessageByHandler(String message){

		messageData = message;
		if( "undefined".equals(message) || message.equals("")) return;

		returnData = new JsonParser().parse(message).getAsJsonObject();
		Log.e("e",returnData.toString());
		String type = returnData.get("type").getAsString();

		if(type.equals("window")){
			if (returnData.get("text").getAsString().startsWith("ver1.0")) {//发送绑定的KEY
				mSocketClient.sendMsg(getApp().getWzkey());
				return;
			}
			//兼容开放JSON协议之前的登录方式
			if ( returnData.get("text").getAsString().startsWith("verifythrough") ) {//验证通过
				renderCore.renderVerifythroughX(message);
				return;
			}

		}


		for(String e: takeMessageHandler.keySet() ){
			takeMessageHandler.get(e).takeMessage(type,message);
		}


	}


	@JavascriptInterface
	public void onTakeMessage(String message) {   //提供给js调用的方法


		Message msg = new Message();
		Bundle data = new Bundle();
		data.putString("msg", message);

		msg.setData(data);
		//收到JS推送来的消息进行处理
		msg.what = 2;
		handler.sendMessage(msg);
		Log.i("onTakeMessage",message);


	}
	private boolean putMessageActionStat = false;
	public void putMessage(String result) {

		for(String e : appMessageHandler.keySet()){
			putMessageActionStat = appMessageHandler.get(e).takeMessage(result);
			if(putMessageActionStat) return;
		}
		this.webView.loadUrl("javascript:takeMessage('" + result + "')");
	}



	public ArrayList<String> mPlaceKey;







	@Override
	public void sendActionToServer(final String action) {


		if (action != null) {
			String[] arys;


			getmAlertGrid().getDataAdapter().clear();
			getmAlertList().getDataAdapter().clear();
			closeAlertBox();


			//判断是否是多个指令
			if(action.contains("\n")){
				arys = action.split("\n");
				for(int i=0;i<arys.length;i++){
					mSocketClient.sendMsg(arys[i]);
				}
			}else{
				mSocketClient.sendMsg(action.trim());
			}

		}
	}

	@Override
	public void onSendTagToServerClick(final String tag) {
		// TODO Auto-generated method stub
		if (tag != null) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					//tag.getBytes("gbk");
					try{

						String tmp = tag;
						String[] tmp2;

						//发送长按
						if ( tag.contains("clickLong") ){

							mSocketClient.sendMsg(currentFooterButAction+" "+tag);
							return;
						}

						if (tmp.contains(";"))
						{
							tmp2 = tmp.split(";");

							for(String s : tmp2)
							{
								mSocketClient.sendMsg(s);
							}

						}else{
							mSocketClient.sendMsg(tag);
						}


						//mSocketClient.sendMsg(new String(tag.getBytes("utf-8"),"iso8859-1"));

						/*
						List<String> cmds = new ArrayList<String>();
						cmds.add("s");
						cmds.add("n");
						for(String cmd :cmds)
						{
							mSocketClient.sendMsg(cmd);
						}
					*/


					}catch (Exception e){

					}

				}
			}).start();
		}
	}








	@Override
	protected void onDestroy() {
			super.onDestroy();
			if(broadcastReceiver!=null){
				broadcastReceiver.endObserver();
				Log.i("test", "注销");
			}
	}





	//server
	// 本方法判断自己些的一个Service-->com.android.controlAddFunctions.PhoneService是否已经运行
	public boolean isWorked() {
		ActivityManager myManager = (ActivityManager) this.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
				.getRunningServices(Integer.MAX_VALUE);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString().equals("com.xlh.outside.MyService")) {
				return true;
			}
		}
		return false;
	}








	public void setExitButEvt(){

		String controlName;
		for(TextView e : exitsMap.keySet()){

			e.setOnClickListener(onDirAreaClickListener);
			e.getLayoutParams().width = FUti.dip2px(this,dirArea.getLayoutParams().width / 3);
			e.getLayoutParams().height =FUti.dip2px(this,30);
//			e.setTextColor(Color.parseColor(Constant.getAppColor().getFontColor()));
//			//获取控件名
//			controlName = e.getClass().getSimpleName();
//
//
//			drawable = (GradientDrawable) e.getBackground();
//			//设置边框
//			drawable.setStroke(FUti.dip2px(this,1), Color.parseColor(Constant.getAppColor().getButBorderColor()));
//			//设置背景
//			drawable.setColor(Color.parseColor(Constant.getAppColor().getButBackColor()));

		}



	}

	public void setAppColor() {
		//主体背景色


		mainLinearLayout= (LinearLayout)findViewById(R.id.all_main);
		mainLinearLayout.setBackgroundColor(  Color.parseColor( Constant.getAppColor().getBackColor())  );


		//线条颜色
		//#CD853F 竖向条
		findViewById(R.id.leftLine1).setBackgroundColor(Color.parseColor(Constant.getAppColor().getLineColor()));
		findViewById(R.id.line2).setBackgroundColor( Color.parseColor(Constant.getAppColor().getLineColor()) );
		findViewById(R.id.line3).setBackgroundColor( Color.parseColor(Constant.getAppColor().getLineColor()) );
		findViewById(R.id.line4).setBackgroundColor( Color.parseColor(Constant.getAppColor().getLineColor()) );
		findViewById(R.id.line5).setBackgroundColor( Color.parseColor(Constant.getAppColor().getLineColor()) );
		findViewById(R.id.line6).setBackgroundColor( Color.parseColor(Constant.getAppColor().getLineColor()) );

		//左侧NPC


		GradientDrawable drawable = (GradientDrawable) mAlertLayout.getBackground();
		mAlertText.setTextColor(Color.parseColor(Constant.getAppColor().getFontColor()));
		tvTop.setTextColor(Color.parseColor(Constant.getAppColor().getFontColor()));
		drawable = (GradientDrawable) tvTop.getBackground();

		//设置边框
		drawable.setStroke(FUti.dip2px(this,1), Color.parseColor(Constant.getAppColor().getButBorderColor()));
		//设置背景
		drawable.setColor(Color.parseColor(Constant.getAppColor().getButBackColor()));


		tvBottom.setTextColor(Color.parseColor(Constant.getAppColor().getFontColor()));


		//发送消息按钮
		drawable = (GradientDrawable) inputBoxBut.getBackground();
		inputBoxBut.setTextColor(Color.parseColor(Constant.getAppColor().getFontColor()));
		//设置边框
		drawable.setStroke(FUti.dip2px(this,1), Color.parseColor(Constant.getAppColor().getButBorderColor()));
		//设置背景
		drawable.setColor(Color.parseColor(Constant.getAppColor().getButBackColor()));
		ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) inputBoxBut.getLayoutParams();
		p.setMargins(0,FUti.dip2px(this,8),0,FUti.dip2px(this,8));





		drawable = (GradientDrawable) tvBottom.getBackground();
		//设置边框
		drawable.setStroke(FUti.dip2px(this,1), Color.parseColor(Constant.getAppColor().getButBorderColor()));
		//设置背景
		drawable.setColor(Color.parseColor(Constant.getAppColor().getButBackColor()));



		drawable = (GradientDrawable) mAlertLayout.getBackground();
		//设置边框
		//drawable.setStroke(FUti.dip2px(this,4), Color.parseColor(Constant.getAppColor().getAlertBoxBorderColor()));
		//设置背景
		drawable.setColor(Color.parseColor(Constant.getAppColor().getAlertBoxBackColor()));



		//地图框
		drawable = (GradientDrawable) mMapLayout.getBackground();
		//设置边框
		//drawable.setStroke(FUti.dip2px(this,4), Color.parseColor(Constant.getAppColor().getAlertBoxBorderColor()));
		//设置背景
		drawable.setColor(Color.parseColor(Constant.getAppColor().getAlertBoxBackColor()));



		String controlName;
		for(TextView e : exitsMap.keySet()){

			e.setOnClickListener(onDirAreaClickListener);
			e.getLayoutParams().width = FUti.dip2px(this,dirArea.getLayoutParams().width / 3);
			e.getLayoutParams().height =FUti.dip2px(this,30);
			e.setTextColor(Color.parseColor(Constant.getAppColor().getFontColor()));
			//获取控件名
			controlName = e.getClass().getSimpleName();


			drawable = (GradientDrawable) e.getBackground();
			//设置边框
			drawable.setStroke(FUti.dip2px(this,1), Color.parseColor(Constant.getAppColor().getButBorderColor()));
			//设置背景
			drawable.setColor(Color.parseColor(Constant.getAppColor().getButBackColor()));

		}




	}



	//关闭弹出窗
	public void closeAlertBox(){



		this.getmAlertGrid().getDataAdapter().clear();
		this.getmAlertList().getDataAdapter().clear();
		if (mAlertLayout.getVisibility() == View.VISIBLE) {
			mAlertLayout.setVisibility(View.INVISIBLE);
			mAlertLayout.setClickable(false);
		}


		//显示弹窗的文字部分，占位隐藏的情况下
		if (mAlertText!=null && mAlertText.getVisibility() == View.VISIBLE) {
			mAlertText.setVisibility(View.GONE);
		}


		mAlertInputBigText.setVisibility(View.GONE);
		mAlertInputBigText.setText("");

		if (mAlertLayout != null && mAlertLayout.getVisibility() == View.VISIBLE) {
					mAlertLayout.setVisibility(View.INVISIBLE);
					mAlertLayout.setClickable(false);

		}

		if (mInputLayout.getVisibility() == View.VISIBLE) {
			mInputLayout.setVisibility(View.INVISIBLE);
			mInputLayout.setClickable(false);
		}

		m091Tv.setVisibility(View.GONE);

		m091Tv.setText("");


	}



	/**
	 * Listener stment===================================================================================
	 */


	/**
	 * 方向键区右侧按钮点击事件
	 */
	private OnClickListener onAdditionalButClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.tvTop:

					if( gdUserBtnArea.getVisibility()==View.GONE ){
						gdUserBtnArea.setVisibility(View.VISIBLE);
						dirArea.setVisibility(View.GONE);
					}else{
						gdUserBtnArea.setVisibility(View.GONE);
						dirArea.setVisibility(View.VISIBLE);
					}


					break;

				case R.id.tvBottom:

					mSocketClient.sendMsg("map view");
					break;
			}
		}
	};



	//方向键被点击
	private View.OnClickListener onDirAreaClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if(v.getTag()==null) return;//防止报错
			sendActionToServer( v.getTag().toString() );

		}
	};


	/**
	 * 隐藏设置风格的FMG
	 */
	public void hideSetColorMain(){
		gamescene.setVisibility(View.VISIBLE);
		fullsceneContainer.setVisibility(View.GONE);
		getFragmentManager().beginTransaction().remove(setColorMainFragment);
		getFragmentManager().beginTransaction().commit();
	}


	//初始化出口按钮区域
	public void initDirControl(){


		dirArea = (LinearLayout) findViewById(R.id.dir_area);
		int w = getApp().getWndWidth() - mTitleList.getLayoutParams().width;
		dirArea.getLayoutParams().width = (w / 100) * 75;

		exitsMap = HashMultimap.create();

		dirTv01 = (TextView) findViewById(R.id.ESA003_01);
		dirTv02 = (TextView) findViewById(R.id.ESA003_02);
		dirTv03 = (TextView) findViewById(R.id.ESA003_03);
		dirTv05 = (TextView) findViewById(R.id.ESA003_05);
		dirTv04 = (TextView) findViewById(R.id.ESA003_04);
		dirTv06 = (TextView) findViewById(R.id.ESA003_06);
		dirTv07 = (TextView) findViewById(R.id.ESA003_07);
		dirTv08 = (TextView) findViewById(R.id.ESA003_08);
		dirTv09 = (TextView) findViewById(R.id.ESA003_09);
		//绑定方向
		//Multimap 可以一键多值
		exitsMap.put(dirTv01,"northwest");


		exitsMap.put(dirTv02,"north");



		exitsMap.put(dirTv03,"northeast");


		exitsMap.put(dirTv04,"west");


		exitsMap.put(dirTv05,"center");

		exitsMap.put(dirTv06,"east");




		exitsMap.put(dirTv07,"southwest");



		exitsMap.put(dirTv08,"south");


		exitsMap.put(dirTv09,"southeast");



		//用户按钮区域
		gdUserBtnArea = (GridView)findViewById(R.id.gr_user_btn_area);
		gdUserBtnArea.getLayoutParams().width =    (w / 100) * 75;

		//隐藏
		gdUserBtnArea.setVisibility(View.GONE);
		userBtnAreaAdapter = new UserBtnAreaAdapter(this,null);
		gdUserBtnArea.setAdapter(userBtnAreaAdapter);

	}




	//出口按钮
	public  TextView getDirTv01() {
		return dirTv01;
	}
	public void     setDirTv01(TextView dirTv01) {
		this.dirTv01 = dirTv01;
	}
	public TextView getDirTv02() {
		return dirTv02;
	}
	public void     setDirTv02(TextView dirTv02) {
		this.dirTv02 = dirTv02;
	}
	public TextView getDirTv03() {
		return dirTv03;
	}
	public void     setDirTv03(TextView dirTv03) {
		this.dirTv03 = dirTv03;
	}
	public TextView getDirTv04() {
		return dirTv04;
	}
	public void     setDirTv04(TextView dirTv04) {
		this.dirTv04 = dirTv04;
	}
	public TextView getDirTv05() {
		return dirTv05;
	}
	public void     setDirTv05(TextView dirTv05) {
		this.dirTv05 = dirTv05;
	}
	public TextView getDirTv06() {
		return dirTv06;
	}public void     setDirTv06(TextView dirTv06) {
		this.dirTv06 = dirTv06;
	}public TextView getDirTv07() {
		return dirTv07;
	}public void     setDirTv07(TextView dirTv07) {
		this.dirTv07 = dirTv07;
	}public TextView getDirTv08() {
		return dirTv08;
	}public void     setDirTv08(TextView dirTv08) {
		this.dirTv08 = dirTv08;
	}public TextView getDirTv09() {
		return dirTv09;
	}public void     setDirTv09(TextView dirTv09) {
		this.dirTv09 = dirTv09;
	}private TextView dirTv01;
	private TextView dirTv02;
	private TextView dirTv03;
	private TextView dirTv04;
	private TextView dirTv05;
	private TextView dirTv06;
	private TextView dirTv07;
	private TextView dirTv08;
	private TextView dirTv09;
	public LinearLayout  dirArea;

	//用户自定义按钮区
	public GridView gdUserBtnArea;

	public UserBtnAreaAdapter getUserBtnAreaAdapter() {
		return userBtnAreaAdapter;
	}

	public void setUserBtnAreaAdapter(UserBtnAreaAdapter userBtnAreaAdapter) {
		this.userBtnAreaAdapter = userBtnAreaAdapter;
	}

	private UserBtnAreaAdapter userBtnAreaAdapter;


	private RenderCore renderCore;


	public SetColorMainFragment setColorMainFragment;

	public ColorPickerFragment colorPickerFragment;

	// 切换操作和附近地图
	private TextView tvTop;
	private TextView tvBottom;

	public TextView getTvMap() {
		return tvMap;
	}

	public void setTvMap(TextView tvMap) {
		this.tvMap = tvMap;
	}

	// 查看地图
	private TextView tvMap;

	public MainActivity getMe() {
		return me;
	}

	public void setMe(MainActivity me) {
		this.me = me;
	}

	private ImageView ivCloseMap;

	public LinearLayout getmMapLayout() {
		return mMapLayout;
	}

	public void setmMapLayout(LinearLayout mMapLayout) {
		this.mMapLayout = mMapLayout;
	}

	private LinearLayout mMapLayout;

	public LinearLayout getmInputLayout() {
		return mInputLayout;
	}

	public void setmInputLayout(LinearLayout mInputLayout) {
		this.mInputLayout = mInputLayout;
	}

	private LinearLayout mInputLayout;

	//登录
	private LinearLayout mLogin_main_layout;

	public TextView getmAlertText() {
		return mAlertText;
	}

	public void setmAlertText(TextView mAlertText) {
		this.mAlertText = mAlertText;
	}

	// 弹出框文本
	private TextView mAlertText;
	private ImageView mAlertClose;

	public MyListView getmAlertList() {
		return mAlertList;
	}

	public void setmAlertList(MyListView mAlertList) {
		this.mAlertList = mAlertList;
	}

	//弹框左边按钮listvew
	private MyListView mAlertList;

	public MyGridView getmAlertGrid() {
		return mAlertGrid;
	}

	public void setmAlertGrid(MyGridView mAlertGrid) {
		this.mAlertGrid = mAlertGrid;
	}

	//弹框右边GDV
	private MyGridView mAlertGrid;

	public ScrollView getmAlertLayout() {
		return mAlertLayout;
	}

	public void setmAlertLayout(ScrollView mAlertLayout) {
		this.mAlertLayout = mAlertLayout;
	}

	//弹窗框左边滚动区域
	public ScrollView mAlertLayout;

	private LinearLayout mL;

	public EditText getEtInput() {
		return etInput;
	}

	public void setEtInput(EditText etInput) {
		this.etInput = etInput;
	}

	// 输入框
	private EditText etInput;


	public Button getInputBoxBut() {
		return inputBoxBut;
	}

	public void setInputBoxBut(Button inputBoxBut) {
		this.inputBoxBut = inputBoxBut;
	}

	private Button inputBoxBut;

	public TextView getmAlertInputBigText() {
		return mAlertInputBigText;
	}

	public void setmAlertInputBigText(TextView mAlertInputBigText) {
		this.mAlertInputBigText = mAlertInputBigText;
	}

	private TextView mAlertInputBigText;

	//中部右侧框架
	private RelativeLayout rlCenterRight;




	// 方向键
	public HashMap<String, String> mDirs;



	// 其他出口
	private ListView mLeftExitGroup;

	public TitleAdapter mLeftAdapter;





	/**
	 * 当最底部的菜单按钮被点击时，记录下是那个菜单
	* 记录内容为 菜单按钮的action值
	* 作用:当用户长按功能键重定义按钮指令时
	* 向服务器发送
	* 菜单action 功能键ID
	* 作用方便服务器记录是那个菜单的按钮被长按了
	*/
	public String currentFooterButAction;

	public SocketClient mSocketClient;




	// 002 地址
	private ListView mTitleList;
	//NPC按钮数据mTitleAdapter
	public NPCAdapter mTitleAdapter;

	public List<TitleBean> getmTitleData() {
		return mTitleData;
	}

	public void setmTitleData(List<TitleBean> mTitleData) {
		this.mTitleData = mTitleData;
	}

	private List<TitleBean> mTitleData;


	// 场景描述
	public TextView tvContent;


    /**
	 * ==================================
	 * 聊天框
	 * =================================
	 */
	public ListView mChatList;
	public ChatAdapter mChatAdapter;
	public List<CharBean> mChatBean;

	public ListView getmCenterList() {
		return mCenterList;
	}

	public void setmCenterList(ListView mCenterList) {
		this.mCenterList = mCenterList;
	}

	// 内容独白
	private ListView mCenterList;

	public boolean isLoginStat() {
		return loginStat;
	}

	public void setLoginStat(boolean loginStat) {
		this.loginStat = loginStat;
	}

	public CenterAdapter getmCenterAdapter() {
		return mCenterAdapter;
	}

	public void setmCenterAdapter(CenterAdapter mCenterAdapter) {
		this.mCenterAdapter = mCenterAdapter;
	}

	private CenterAdapter mCenterAdapter;

	public List<CenterText> getmCenterData() {
		return mCenterData;
	}

	public void setmCenterData(List<CenterText> mCenterData) {
		this.mCenterData = mCenterData;
	}

	private List<CenterText> mCenterData;
	// 颜色值
	public Map<String, String> mColors;
	// 匹配值
	public List<String> mColorList;

	public LinearLayout mainLinearLayout;

	//右边浮动LISTVIEW
	public ListView lvFloatRightList;
	public FloatingMenu floating;




	// 底部按钮组
	public LinearLayout mBtnGroup;





	public WzTextView m091Tv;





	private boolean isAddPro = false;


	/**
	 * 当前activi是否运行
	 */
	private boolean runing = false;


	/**
	 * 登陆状态检查
	 */
	public static boolean isLogin = false;

	private static int serverType = 1;//1为手机 2为PC

	private boolean sceneViewHide;
	//场景框默认高度
	private int sceneViewOldHeight;

	/**
	 * 是否需要重连 重连状态
	 */
	private boolean reconnectStatus = false;
	//出口集合 非线程安全
	//public Map<String,TextView> exitsMap = new HashMap<String,TextView>();
	//public Multimap<TextView,String> exitsMap = new HashMap<TextView,String>();
	public Multimap<TextView,String> exitsMap;
	public WzBroadcastReceiver broadcastReceiver;

	/**
	 *游戏视图
	 */
	public LinearLayout gamescene;

	/**
	 * 全屏容器
	 *
	 */
	public LinearLayout fullsceneContainer;
	//只能这样丑陋的记住008的宽度
	public int list008Weight=1;

	//全局中被点击的BUTID
	private String activeButKey;

	public List<ButCmd> getDiyButs() {
		return diyButs;
	}

	public void setDiyButs(List<ButCmd> diyButs) {
		this.diyButs = diyButs;
	}

	//全局自定义按键
	private List<ButCmd> diyButs = new ArrayList<ButCmd>();



	public String getActiveButKey() {
		return activeButKey;
	}

	public void setActiveButKey(String activeButKey) {
		this.activeButKey = activeButKey;
	}

	public UserFg getUserFg() {
		return userFg;
	}

	public void setUserFg(UserFg userFg) {
		this.userFg = userFg;
	}

	private UserFg userFg;












	@Override
	public MainActivity getActivity() {
		return this;
	}
}
